<template>
    <div class="app-container">
        <el-form ref="searchForm" inline :model="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="名称：" prop="name">
                        <el-input clearable v-model="searchForm.name" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-button @click="init('search')" type="primary">查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick" type="primary" style="position: absolute;right: 0;">添加角色</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin-bottom: 20px;">
            <el-table-column type="index" width="40" align="center"></el-table-column>
            <el-table-column prop="name" label="名称" align="center"></el-table-column>
            <el-table-column prop="description" label="描述" show-overflow-tooltip align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" width="340" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" type="primary" plain size="mini">编辑</el-button>
                    <el-button @click.stop="roleSetClick(scope.row)" type="primary" plain size="mini">权限设置</el-button>
                    <el-button @click.stop="memberSetClick(scope.row)" type="primary" plain size="mini">成员设置</el-button>
                    <el-button @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!--  编辑 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="dataForm.name" maxlength="30" placeholder="必填项。请输入名称，最大长度为30"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="description">
                    <el-input v-model="dataForm.description" type="textarea" :rows="4" maxlength="500" placeholder="请输入描述，最大长度为500"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 成员 弹框 -->
        <el-dialog :visible.sync="memberShowDialog" width="800px">
            <el-form ref="memberForm" :rules="memberrules" :model="memberForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="手机号：" prop="userPhone" v-show="popStatus == 0">
                    <el-input v-model="userPhone" maxlength="11" placeholder="请输入手机号"><el-button type="primary" slot="append" @click="userList">查询</el-button></el-input>
                </el-form-item>
                <el-form-item label="用户：" prop="sysUserId">
                    <el-row>
                        <el-col :span="20"><el-input v-model="sysUserName" disabled placeholder="必填项。查询手机号获取用户信息"></el-input></el-col>
                        <el-col :span="4"><el-button type="primary" @click="addUser" style="display: inline-block;margin-left: 10px;">添加成员</el-button></el-col>
                    </el-row>
                </el-form-item>
            </el-form>
            <!-- 成员列表 -->
            <el-table :data="memberList" border style="width: 100%;margin-bottom: 20px;">
                <el-table-column type="index" align="center"></el-table-column>
                <el-table-column prop="userName" label="昵称" align="center"></el-table-column>
                <el-table-column label="操作" width="150" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click.stop="delMemberClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination @current-change="memberGetList" layout="total, prev, pager, next, jumper" :total="memberPageData.totalElements"></el-pagination>
        </el-dialog>

        <!--  权限 弹框 -->
        <el-dialog :visible.sync="roleshowDialog" width="800px">
            <el-form ref="roleForm" :model="roleForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-tabs type="border-card">
                    <el-tab-pane label="应用和菜单">
                        <el-form-item label="应用：" prop="application">
                            <el-checkbox-group v-model="roleForm.application">
                                <el-checkbox v-for="(item,index) in applicationOpt" :key="index" :label="item.id">{{item.name}}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="菜单：" prop="menu">
                            <el-tree :data="menuOpt" ref="menu" check-on-click-node show-checkbox node-key="id" @check="menuChange" :default-expanded-keys="menuIdList" :default-checked-keys="menuIdList" :props="defaultProps"></el-tree>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="接口">
                        <el-form-item label="接口：" prop="interface">
                            <el-tree :data="interfaceOpt" ref="interface" check-on-click-node show-checkbox node-key="id" @check="interfaceChange" :default-expanded-keys="interfaceIdList" :default-checked-keys="interfaceIdList" :props="interfaceProps"></el-tree>
                        </el-form-item>
                    </el-tab-pane>
                    <el-form-item>
                        <el-button @click="roleSubmit('roleForm')" type="primary">保存</el-button>
                        <el-button @click="cancelClick('roleForm')">取消</el-button>
                    </el-form-item>
                </el-tabs>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { addRecord, findRecord, detailRecord, editRecord, delRecord, getPermissionRecord } from '@/api/system/permission/role-set'
import { getOverviewRecord } from '@/api/user-management/sys-user'
import { findApplication, findListApplication } from '@/api/application/application'
import { findInterface } from '@/api/system/permission/interface'
import { addMemberRecord,findMemberRecord,delMemberRecord } from '@/api/system/permission/sys-role-member'
import { editPermissionRecord,findAppRecord,findInterfaceRecord,findMenuRecord } from '@/api/system/permission/sys-role-permission'
import { getCookie, setCookie } from '@/utils/auth'
export default {
    name: 'SysRole',
    data() {
        return{
            tableData: [],
            nowId: '',
            showDialog: false,
            dataForm: {
                description: '',
                name: '',
            },
            rules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ],
            },
            searchForm:{name: '',},
            nowPage: 0,
            pageSize: 10,
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            memberShowDialog:false,
            memberForm: {sysUserId: ''},
            memberrules: {
                sysUserId: [
                    { required: true, message: '请选择用户', trigger: 'blur' }
                ],
            },
            userPhone: '',
            roleshowDialog: false,
            roleForm: {application: [],menu: [], interface: [],},
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            interfaceProps: {
                children: 'children',
                label: 'description'
            },
            applicationOpt: [],
            menuOpt: [],
            interfaceOpt: [],
            sysUserName: '',
            memberList: [],
            roleId: '',
            interfaceIdList: [],
            menuIdList: [],
            memberNowPage: 0,
            memberPageSize: 10,
            memberPageData: {},
            menuIdArr: []
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            //获取列表信息
            findRecord(_this.nowPage, _this.pageSize, _this.searchForm.name ).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object;
                    _this.tableData = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取用户信息
        userList(){
            const _this = this;
            _this.memberForm.sysUserId = '';
            _this.sysUserName = '';
            getOverviewRecord(_this.userPhone).then(response => {
                if(response.code == 200){
                    _this.memberForm.sysUserId = response.object.id;
                    _this.sysUserName = response.object.nickName;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取接口
        interfaceList(){
            const _this = this;
            //获取列表信息
            findInterface(0, 10000,'','','' ).then(response => {
                if(response.code == 200){
                    _this.interfaceOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取应用
        applicationList(){
            const _this = this;
            //获取列表信息
            findApplication({ page: 0, size: 10000, name: '' }).then(response => {
                if(response.code == 200){
                    _this.applicationOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取菜单
        menuList(){
            const _this = this;
            //获取列表信息
            findListApplication().then(response => {
                if(response.code == 200){
                    const obj = response.object
                    _this.menuOpt = obj
                    for(let i=0; i<obj.length; i++){
                        _this.menuOpt[i].children = obj[i].appNavBarEntityList
                        for(let j=0; j<obj[i].appNavBarEntityList.length; j++){
                            _this.menuOpt[i].appNavBarEntityList[j].children = obj[i].appNavBarEntityList[j].appNavMenuEntityList
                        }
                    }
                    _this.menuIdArr = []
                    _this.getTreeData(_this.menuOpt)
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(let i=0;i<data.length;i++){
                this.menuIdArr.push(data[i].id)
                if(data[i].children && data[i].children.length>0){
                    this.getTreeData(data[i].children)
                }
            }
        },
        //添加
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.dataForm.description = '',
            this.dataForm.name = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //提交添加
        addSubmit(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    if(_this.popStatus == 0){  //添加
                        addRecord(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editRecord(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            const _this = this;
            this.$confirm('确定删除 '+row.name+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delRecord(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //  删除成员
        delMemberClick(row){
            const _this = this
            this.$confirm('确定删除 '+row.userName+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delMemberRecord(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message)
                        _this.memberPageList()
                    }else{
                        this.$message.error(response.message)
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                })         
            })
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.dataForm.description = row.description;
            this.dataForm.name = row.name;
            this.showDialog = true;
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.roleshowDialog = false;
            this.memberShowDialog = false;
            this.$refs[formName].resetFields();
        },
        //设置权限
        roleSetClick(row){
            const _this = this;
            _this.roleId = row.id;
            //应用
            findAppRecord(_this.roleId).then(response => {
                if(response.code == 200){
                    _this.roleForm.application = [];
                    if(response.object){
                        for(let i=0;i<response.object.length;i++){
                            _this.roleForm.application.push(response.object[i].id);
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
            //菜单
            findMenuRecord(_this.roleId).then(response => {
                if(response.code == 200){
                    _this.menuIdList = [];
                    _this.$refs.menu.setCheckedKeys([]);
                    if(response.object){
                        for(let i=0;i<response.object.length;i++){
                            // if(_this.menuIdArr.indexOf(response.object[i].id) !== -1){
                                _this.menuIdList.push(response.object[i].id)
                            // }
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
            //接口
            findInterfaceRecord(_this.roleId).then(response => {
                if(response.code == 200){
                    _this.interfaceIdList = [];
                    this.$refs.interface.setCheckedKeys([]);
                    if(response.object){
                        for(let i=0;i<response.object.length;i++){
                            _this.interfaceIdList.push(response.object[i].id);
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
            
            this.roleshowDialog = true;
        },
        //添加成员
        addUser(){
            const _this = this
            if(this.memberForm.sysUserId == ''){
                this.$message.info('请先通过手机号查取对应的用户');
                return
            }
            const arr = []
            arr.push(this.memberForm.sysUserId)
            addMemberRecord({ roleId: this.roleId, userIdList: arr }).then(response => {
                if(response.code == 200){
                    this.$message.success(response.message)
                    _this.memberPageList()
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //删除成员
        handleClose(index) {
            this.memberList.splice(index, 1);
        },
        //设置成员
        memberSetClick(row){
            this.roleId = row.id
            this.memberPageList()
            this.memberShowDialog = true;
        },
        // 成员列表
        memberPageList(){
            const _this = this
            findMemberRecord(_this.memberNowPage,_this.memberPageSize,_this.roleId).then(response => {
                if(response.code == 200){
                    _this.memberPageData = response.object
                    if(response.object.content){
                        _this.memberList = response.object.content
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //菜单 change
        menuChange(value,arr){
            this.menuIdList = arr.checkedKeys;
        },
        //接口 change
        interfaceChange(value,arr){
            this.interfaceIdList = arr.checkedKeys;
        },
        //权限保存
        roleSubmit(){
            const _this = this;
            // console.log(this.$refs.menu.getCheckedKeys(),'------------选择')
            // console.log(_this.menuIdList,'------------菜单')
            editPermissionRecord({ appIdList: _this.roleForm.application, menuIdList: _this.$refs.menu.getCheckedKeys(), interfaceIdList: _this.interfaceIdList, roleId: _this.roleId }).then(response => {
                if(response.code == 200){
                    this.$message.success(response.message);
                    _this.init();
                    _this.roleshowDialog = false;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        // 成员分页
        memberGetList(val){
            this.memberNowPage = val - 1;
            this.memberPageList();
        },
    },
    mounted(){
        this.init();
        this.applicationList();
        this.menuList();
        this.interfaceList();
    }
}
</script>